//
//  ThirdLogin.m
//  game
//
//  Created by yun on 2018/3/14.
//  Copyright © 2018年 YD. All rights reserved.
//

#import "ThirdLogin.h"
#import "WXATModel.h"

#define kWeChatAppId @"kWeChatAppId"
#define kWeChatAppSecret @"kWeChatAppSecret"

#define kTencentAppId @"kTencentAppId"

@interface ThirdLogin ()

@property (nonatomic,strong) TencentOAuth *tencentOAuth;
@property (nonatomic,strong) NSMutableArray *tencentPermissions;

@property (nonatomic,copy) NSString *access_token;
// 登录回调
@property (nonatomic,copy) void (^loginReslut)(id responseObject, NSError *error);

@end

@implementation ThirdLogin

static ThirdLogin *manager;

+ (instancetype)sharedManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
        [manager setUpConfiguration];
    });
    return manager;
}

// 注册app
- (void)setUpConfiguration{
    // 微信注册
    [WXApi registerApp:kWeChatAppId];
    
    // 注册QQ
    self.tencentOAuth = [[TencentOAuth alloc] initWithAppId:kTencentAppId andDelegate:self];
    // 这个是说到时候你去qq拿信息的类型
    self.tencentPermissions = [NSMutableArray arrayWithArray:@[/** 获取用户信息 */
                                                           kOPEN_PERMISSION_GET_USER_INFO,
                                                           /** 移动端获取用户信息 */
                                                           kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
                                                           /** 获取登录用户自己的详细信息 */
                                                           kOPEN_PERMISSION_GET_INFO]];
}

// 点击登录
- (void)getUserInfoWithLoginType:(LYLoginType)type result:(void (^)(id responseObject, NSError *error))result{
    
    self.loginReslut = result;
    if (type == LYLoginTypeWeChat) {
        //构造SendAuthReq结构体
        SendAuthReq *req =[[SendAuthReq alloc] init];
        req.scope = @"snsapi_userinfo" ;
        //第三方向微信终端发送一个SendAuthReq消息结构
        [WXApi sendReq:req];
    } else if (type == LYLoginTypeTencent){
        // 登录授权
        [self.tencentOAuth authorize:self.tencentPermissions];
    }
    
}

#pragma mark -- WXApiDelegate

- (void)onResp:(BaseResp*)resp{
    SendAuthResp *aresp = (SendAuthResp *)resp;
    if (resp.errCode == WXSuccess){// 成功
        [[ThirdLogin sharedManager] getWeChatTokenWithCode:aresp.code];
    } else{
        if (self.loginReslut) {
            NSError *err = [NSError errorWithDomain:@"授权失败" code:100 userInfo:nil];
            self.loginReslut(nil, err);
        }
    }
}

// 获取微信token
- (void)getWeChatTokenWithCode:(NSString *)code{
    
    [NetWorkManager getRequestForUrl:[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",kWeChatAppId,kWeChatAppSecret,code] completion:^(id responseObject, NSError *error) {
        if (error) {// 错误
            if (self.loginReslut) {
                self.loginReslut(nil, error);
            }
        } else {
//            WXATModel *model = [WXATModel mj_objectWithKeyValues:responseObject];
            WXATModel *model = [[WXATModel alloc] init];
            [model setValuesForKeysWithDictionary:responseObject];
            self.access_token = model.access_token;
            [self getWeChatUserInfo];
        }

    }];
}

// 获取用户信息
- (void)getWeChatUserInfo{
    [NetWorkManager getRequestForUrl:[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",self.access_token,kWeChatAppId] completion:^(id responseObject, NSError *error) {
        if (self.loginReslut) {
            self.loginReslut(responseObject, error);
        }
    }];
}

#pragma mark - TencentSessionDelegate

// 登录成功后的回调
- (void)tencentDidLogin {
    if (self.tencentOAuth.accessToken && self.tencentOAuth.accessToken.length > 0) {
        [self.tencentOAuth getUserInfo];// 获取用户个人信息
    } else {
        if (self.loginReslut) {
            NSError *err = [NSError errorWithDomain:@"授权失败" code:100 userInfo:nil];
            self.loginReslut(nil, err);
        }
    }
}

/**
 * 获取用户个人信息回调
 * \param response API返回结果，具体定义参见sdkdef.h文件中\ref APIResponse
 * \remarks 正确返回示例: \snippet example/getUserInfoResponse.exp success
 *          错误返回示例: \snippet example/getUserInfoResponse.exp fail
 */
- (void)getUserInfoResponse:(APIResponse*)response{
    if (response.retCode == URLREQUEST_SUCCEED) {
        if (self.loginReslut) {
            self.loginReslut(response, nil);
        }
    } else {
        if (self.loginReslut) {
            NSError *err = [NSError errorWithDomain:@"登录失败" code:100 userInfo:nil];
            self.loginReslut(nil, err);
        }
    }
}

/**
 * 登录失败后的回调
 * \param cancelled 代表用户是否主动退出登录
 */
- (void)tencentDidNotLogin:(BOOL)cancelled {
    
    if (self.loginReslut) {
        NSError *err;
        if (cancelled) {
            err = [NSError errorWithDomain:@"用户取消登录" code:100 userInfo:nil];
        } else {
            err = [NSError errorWithDomain:@"登录失败" code:100 userInfo:nil];
        }
        self.loginReslut(nil, err);
    }
}

/**
 * 登录时网络有问题的回调
 */
- (void)tencentDidNotNetWork { 
    if (self.loginReslut) {
        NSError *err = [NSError errorWithDomain:@"网络错误" code:100 userInfo:nil];
        self.loginReslut(nil, err);
    }
}



@end
